const Service = require('egg').Service;
function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}



function add0(m){return m<10?'0'+m:m }

// 时间戳 转 时分秒
function formatDate(dateTime) {
    var time = new Date(dateTime);
    const y = time.getFullYear();
    const m = time.getMonth()+1;
    const d = time.getDate();
    const h = time.getHours();
    const mm = time.getMinutes();
    const s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}

// 前端提交过来的数据要求 判断用
const createRule = {
    action: { type: 'string' },
    action_id: { type: 'string' },
    amount:  { type: 'string' },
    sign: { type: 'string' },
    userAddress_id: { type: 'string' },
    contract_id: { type: 'string' },
    isBuy: { type: 'string' },
    dateTime: { type: 'string' }
};

// @URL GET /index validate
const listRule = {
    limit: { type: 'string' },
    offset: { type: 'string' },
    userAddress_id: { type: 'string' },
    contract_id: { type: 'string' },
};

// @URL GET /hotel validate
const createHotelRule = {
    action_id: { type: 'string' },
    amount:  { type: 'string' },
    sign: { type: 'string' },
    userAddress_id: { type: 'string' },
    contract_id: { type: 'string' },
    dateTime: { type: 'string' }
};

class ActionService extends Service {
    // 列表条件搜索展示
    async list(limit, offset, order, userAddress_id, contract_id, dataValidate) {
        this.ctx.validate(listRule, dataValidate);

        const query_index = {
            limit: toInt(limit),
            offset: toInt(offset),
            order: [
                [order, 'DESC']
            ],
            where: {
                userAddress_id: userAddress_id,
                contract_id:  contract_id
            }
        };
        // ctx.body = ctx.service.action.get(query_index);
        const res = await this.ctx.model.Action.findAll(query_index);
        return res;
    }


    // 冻结金额
    async blockedBalance(userAddress_id, contract_id, struct_id ) {
        const query_action_unique = {
            where: {
                userAddress_id:  userAddress_id,
                contract_id:  contract_id,
                struct_id:  struct_id
            }
        };
        // 循环用的数组
        const res_sum = await this.ctx.model.Action.findAll(query_action_unique);
        // ctx.body = res_sum;

        var add = 0;
        // 获取符合条件的
        res_sum.forEach(async function (row) {
            add += parseFloat(row.amount);
        });
        // return add;
        // ctx.status = 200;
        return add;
    }


    async create(balance, setTimeFive) {
        const ctx = this.ctx;
      
        // 目前只是验证 传值了没有
        ctx.validate(createRule, ctx.request.body);

        // 首先判断余额够这次下单的吗
        const query_data = {
            where: {
                userAddress_id:  ctx.request.body.userAddress_id,
                contract_id:  ctx.request.body.contract_id,
                struct_id:  0
            }
        };
        // 循环用的数组
        const res_sum = await ctx.model.Action.findAll(query_data);
        // ctx.body = res_sum;
        let add = 0;
        if(res_sum) {
            res_sum.forEach(async function (row) {
                add += parseFloat(row.amount);
            });
        }

        const res_hotel = await ctx.model.Hotel.findAll(query_data);
        let add_hotel = 0;
        if(res_hotel) {
            res_hotel.forEach(async function (row) {
                add_hotel += parseFloat(row.amount);
            });
        }
        // ctx.status = 201;
        if(parseFloat(balance) < parseFloat(ctx.request.body.amount) + add + add_hotel) {
            return {'status_code':200, 'msg': '余额不充足,请先充值！'};
        }
        // 判断 action_id 是否存在 不存在执行下面
        const query = {
            where: {
                action_id: ctx.request.body.action_id
            }
        };
        //
        const res = await ctx.model.Action.findAll(query);

        if(res.length != 0) {
            // ctx.status = 422;
            return {'status_code':422, 'msg': 'action_id 已存在'};
            return;
        }
        // 开盘时间 自己算 | 订单时间我自己本机时间
        const myDate = Date.now();
        ctx.request.body.openTime = (myDate - myDate % setTimeFive);
        ctx.request.body.dateTime = (myDate);
        // 创建
        const { action, action_id, amount, sign,userAddress_id, contract_id, isBuy, dateTime, openTime } = ctx.request.body;
        const Action = await ctx.model.Action.create({ action, action_id, amount, sign,userAddress_id, contract_id, isBuy, dateTime, openTime });
        // 返回值
        ctx.status = 201;
        return Action;
    }
     /**
    * 提现
    * 
    * */
    async hotel(balance) {
        // 统计 action 表中冻结的金额
        const ctx = this.ctx;

        // 目前只是验证 传值了没有
        ctx.validate(createHotelRule, ctx.request.body);

        // 判断 action_id 是否存在 不存在执行下面
        const query = {
            where: {
                action_id: ctx.request.body.action_id
            }
        };
        //
        const res = await ctx.model.Hotel.findAll(query);

        if(res.length != 0) {
            ctx.status = 422;
            return {'status_code':422, 'msg': 'Hotel action_id 已存在'};
        }

        // 首先判断余额够这次下单的吗
        const user_unique = {
            where: {
                userAddress_id:  ctx.request.body.userAddress_id,
                contract_id:  ctx.request.body.contract_id,
                struct_id:  0
            }
        };
        const res_sum = await ctx.model.Action.findAll(user_unique);
        // ctx.body = res_sum;
        let add = 0;
        if(res_sum) {
            res_sum.forEach(async function (row) {
                add += parseFloat(row.amount);
            });
        }
        //
        // 统计 hotel 提现中
        const res_hotel = await ctx.model.Hotel.findAll(user_unique);
        
        let add_hotel = 0;
        if(res_hotel) {
            res_hotel.forEach(async function (row) {
                add_hotel += parseFloat(row.amount);
            });
        }
        // return parseFloat(ctx.request.body.amount) + add_hotel + add;
        // hotel 冻结统计 + actions 冻结统计，
        if(parseFloat(balance) < parseFloat(ctx.request.body.amount) + add_hotel + add) {
            return {'status_code':422, 'msg': '余额不充足,请先充值！'};
            
        }
        const { action_id, amount, sign,userAddress_id, contract_id, dateTime } = ctx.request.body;
        const Hotel = await ctx.model.Hotel.create({ action_id, amount, sign,userAddress_id, contract_id, dateTime });
        // // 返回值
        return Hotel;

    }
}
module.exports = ActionService;